//
// Created by Administrator on 2023/7/31.
//
#include <iostream>
#include <stack>

using namespace std;

class Solution {
public:
    int alternateDigitSum(int n) {
        stack<int> s;
        while (n) {
            s.push(n % 10);
            n /= 10;
        }
        int ans = 0;
        int sign = 1;
        while (!s.empty()) {
            ans += s.top() * sign;
            sign *= -1;
            s.pop();
        }
        return ans;
    }
};

class Solution2 {
public:
    int alternateDigitSum(int n) {
        // 不需要栈  最后乘上一个 -sign
        // 如果长度是奇数，则最后sign是-1，头尾都是正的，-sign = 1;
        // 如果长度是偶数，则最后sign是1，头正尾负，-sign=-1
        int res = 0, sign = 1;
        while (n > 0) {
            res += n % 10 * sign;
            sign = -sign;
            n /= 10;
        }
        return -sign * res;
    }
};


int main() {
    Solution s;
    cout << s.alternateDigitSum(521) << endl;
    cout << s.alternateDigitSum(111) << endl;
    cout << s.alternateDigitSum(886996) << endl;


}